package com.bs.resa.common;

import com.zaxxer.hikari.HikariDataSource;
import io.lettuce.core.dynamic.annotation.Value;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceHelper {
  private Logger log = LoggerFactory.getLogger(DataSourceHelper.class);
  private String driverClassName; // com.mysql.cj.jdbc.Driver
  private String url; // jdbc:mysql://localhost:3306/pybbs?useSSL=false&characterEncoding=utf8
  private String username; // root
  private String password; // password

  @PostConstruct
  public void init() {
    try {
      Class.forName(driverClassName);
      URI uri = new URI(url.replace("jdbc:", ""));
      String host = uri.getHost();
      int port = uri.getPort();
      String path = uri.getPath();
      Connection connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port, username, password);
      Statement statement = connection.createStatement();
      statement.executeUpdate("CREATE DATABASE IF NOT EXISTS `" + path.replace("/", "") + "` DEFAULT CHARACTER SET = `utf8` COLLATE `utf8_general_ci`;");
      statement.close();
      connection.close();
    } catch (URISyntaxException | ClassNotFoundException | SQLException e) {
      log.error(e.getMessage());
    }
  }


}